package com.lrd.snapshotorder.config.redis;

import com.lrd.snapshotorder.util.LocalDateToDateConverter;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.IsoFields;
import java.time.temporal.TemporalField;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class RedissonClientService {

    @Autowired
    @Qualifier(value = "redissonSingle")
    private RedissonClient redissonClient;

    /**
     * 获取redis的queue
     *
     * @return
     */
    public RBlockingDeque getRBlockingDeque(String queueName) {
        return redissonClient.getBlockingDeque(RedisKeyConstants.getBlockingDeque(queueName));
    }

    /**
     * 获取批次号最后两位数值
     *
     * @return
     */
    public Integer getBatchNumberByDate(Date date) {
        LocalDate localDate = LocalDateToDateConverter.convertToLocalDate(date);
        String year = String.valueOf(localDate.getYear()).substring(2);
        TemporalField weekField = IsoFields.WEEK_OF_WEEK_BASED_YEAR;
        int week = localDate.get(weekField);
        RAtomicLong atomicLong = redissonClient.getAtomicLong(RedisKeyConstants.ORDER_BATCH_NUMBER);
        Long autoNumber = atomicLong.incrementAndGet();
        //超过99重置为1
        if (autoNumber > 99) {
            autoNumber = 1L;
            atomicLong.set(autoNumber);
        }
        return Integer.parseInt(year + String.format("%02d", week) + String.format("%02d", autoNumber));
    }

    /**
     * 获取批次号最后两位数值
     *
     * @return
     */
    public String getBatchNumber() {
        // 获取当前时间
        /*LocalDateTime currentDateTime = LocalDateTime.now();
        // 获取当天结束时间（23:59:59）
        LocalDateTime endDateTime = LocalDateTime.of(currentDateTime.toLocalDate(), LocalTime.of(23, 59, 59));
        // 计算时间间隔毫秒数
        Duration duration = Duration.between(currentDateTime, endDateTime);
        long expireMillis = duration.toMillis();*/
        RAtomicLong atomicLong = redissonClient.getAtomicLong(RedisKeyConstants.ORDER_BATCH_NUMBER);
        //atomicLong.expire(expireMillis, TimeUnit.MILLISECONDS);
        Long autoNumber = atomicLong.incrementAndGet();
        //超过99重置为1
        if (autoNumber > 99) {
            autoNumber = 1L;
            atomicLong.set(autoNumber);
        }
        return String.format("%02d", autoNumber);
    }

    public String generateAutoBatchNumber(String key) {
        // 获取当前时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 获取当天结束时间（23:59:59）
        LocalDateTime endDateTime = LocalDateTime.of(currentDateTime.toLocalDate(), LocalTime.of(23, 59, 59));
        // 计算时间间隔毫秒数
        Duration duration = Duration.between(currentDateTime, endDateTime);
        long expireMillis = duration.toMillis();
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        atomicLong.expire(expireMillis, TimeUnit.MILLISECONDS);
        Long autoNumber = atomicLong.incrementAndGet();

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String autoNumberStr = date + String.format("%02d", autoNumber);
        log.info("生成批次号:autoNumberStr={}", autoNumberStr);
        return autoNumberStr;
    }
}
